import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';

import { BehaviorSubject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { NzTreeNode } from 'ng-zorro-antd/tree';

import { BaseDirective } from '../../core/models/base-directive.model';
import { DialogOption } from '../../extensions/elements/dialogs/shared/dialog-option.model';
import { UserService } from '../shared/user.service';

declare const $: any;

@Component({
	selector: 'op-user-list',
	templateUrl: './user-list.component.html'
})
export class UserListComponent extends BaseDirective implements OnDestroy, OnInit {
	formGroup: FormGroup;
	users: any[];
	userDialogVisible: boolean = false;
	imgDialogVisible: boolean = false;
	newDialogVisible: boolean = false;
	userDialogData: DialogOption;
	imgDialogData: DialogOption;
	newDialogData: DialogOption;
	status: string[] = [];
	filteredStatus: string[] = [];
	searchValue: string = '';
	newStatus: string = '';
	nodes: NzTreeNode[] = [];

	constructor(
		private formBuilder: FormBuilder,
		private router: Router,
		private userService: UserService
	) {
		super();
	}

	ngOnInit(): void {
		super.ngOnInit();

		this.users = [
			{ id: 1, name: '张三' },
			{ id: 2, name: '李四' },
			{ id: 3, name: '王五' }
		];

		this.loadData();
		this.createForm();
		this.loadAntTree();
	}

	ngOnDestroy(): void {
		super.ngOnDestroy;
	}

	// handle3(type: string): void {
	//     this.notify.setOptions({ onClose: () => { this.router.navigate(['//foo-demo/material-template-driven-form']) } });
	//     this.notify[type]('这是一条消息提示: ' + type, type)
	// }

	private createForm(): void {
		this.formGroup = this.formBuilder.group({
			searchValue: [''],
		});

		this.formGroup.controls.searchValue.valueChanges.pipe(
			debounceTime(1000),
			distinctUntilChanged()
		).subscribe(result => {
			this.userService.getMatchedStatus({ keyword: result }).subscribe(res => {

				this.status = res.value;
				this.newStatus = result;
				this.filteredStatus = this.filterStates(result);
			});
		});
	}

	getSearchData(event: any): void {
		console.log(event);
	}

	loadData(): void {
		this.userDialogData = {
			width: 500,
			title: 'Dev Demo'
		}

		this.newDialogData = {
			width: 500,
			title: 'new Demo'
		}
	}

	mouseAction(e: any): void {
		console.log(this.newStatus);
		$(".ant-tree-node-content-wrapper").removeClass('ant-tree-node-selected');

		if (e.matchedKeys) {
			if (e.matchedKeys[0]) {
				if (this.newStatus === e.matchedKeys[0].origin.chineseName) {
					$(`span[title="${e.matchedKeys[0].origin.title}"]`).addClass('ant-tree-node-selected');
					this.getOrigin(e.matchedKeys[0].origin);
				}
			}
		}

		if (e.selectedKeys) {
			if (e.selectedKeys[0]) {
				$(`span[title="${e.selectedKeys[0].origin.title}"]`).addClass('ant-tree-node-selected');
				this.getOrigin(e.selectedKeys[0].origin);
			}
		}
	}

	getOrigin(e: any): void {
		console.log(e);
	}

	getStatus(): void {
		if (this.filteredStatus.length < 1) {
			this.formGroup.patchValue({ searchValue: null });
		} else {
			this.formGroup.patchValue({ searchValue: this.filteredStatus[0] });
		}
	}

	// getValue(): void {
	//   if (this.searchValue) {
	//     new BehaviorSubject(this.searchValue).pipe(
	//       debounceTime(1000),
	//       distinctUntilChanged()
	//     ).subscribe(result => {
	//       this.userService.getMatchedStatus({ keyword: result }).subscribe(res => {
	//         this.status = res.value;
	//         this.filteredStatus = this.filterStates(result);
	//       });
	//     });
	//   } else {
	//     this.filteredStatus = [];
	//   }
	// }

	private filterStates(result: string): string[] {
		return this.status.filter(state =>
			state.indexOf(result) >= 0);
	}

	loadAntTree() {
		let antdTree = [];

		let originData = [
			{
				"typeCode": 1,
				"typeName": "公用基础数据",
				"children": [
					{
						"tableName": "BASE_CONST_CODE",
						"chineseName": "基本常量的编码"
					},
					{
						"tableName": "BASE_AREA_INFO",
						"chineseName": "全国各区域信息表"
					},
					{
						"tableName": "BASE_AREA_CODE",
						"chineseName": "全国地区编码表"
					}
				]
			},
			{
				"typeCode": 2,
				"typeName": "企业工商数据",
				"children": [
					{
						"tableName": "EPT_BAS_INFO",
						"chineseName": "企业基本信息资料表"
					},
					{
						"tableName": "EPT_CHG_INFO",
						"chineseName": "企业信息变更表"
					},
					{
						"tableName": "EPT_MAIN_PERSON",
						"chineseName": "企业主要人员表"
					},
					{
						"tableName": "EPT_HOLDER_INFO",
						"chineseName": "企业股东信息"
					},
					{
						"tableName": "EPT_HOLDER_CONTRB",
						"chineseName": "企业股东出资信息"
					},
					{
						"tableName": "EPT_BRANCH_INFO",
						"chineseName": "企业分支机构"
					},
					{
						"tableName": "EPT_ABN_OPRTE_INFO",
						"chineseName": "企业异常经营信息表"
					},
					{
						"tableName": "EPT_ADM_LIC_CRTFC",
						"chineseName": "企业行政许可信息及企业认证信息"
					}
				]
			},
			{
				"typeCode": 3,
				"typeName": "企业信用数据",
				"children": [
					{
						"typeCode": 5,
						"typeName": "处罚类数据",
						"children": [
							{
								"tableName": "PNSHA_ENV_PRTCT",
								"chineseName": "环境保护类行政处罚信息"
							},
							{
								"tableName": "PNSHA_ENV_PRTCT_ATT",
								"chineseName": "环境保护类行政处罚附加信息"
							},
							{
								"tableName": "PNSHA_ORG_TXT",
								"chineseName": "行政处罚决定书原文资料表"
							}
						]
					},
					{
						"typeCode": 6,
						"typeName": "司法类数据"
					}
				]
			},
			{
				"typeCode": 4,
				"typeName": "国际贸易数据",
				"children": [
					{
						"tableName": "TRD_GLOB_BAS_DATA",
						"chineseName": "全球进出口贸易基础数据"
					},
					{
						"tableName": "PNSHJ_COURT_INFO",
						"chineseName": "院基本信息表"
					},
					{
						"tableName": "TRD_STAT_TOTVAL",
						"chineseName": "按国家统计的全球进出口贸易总额"
					},
					{
						"tableName": "PNSHJ_CAUSE_TYP",
						"chineseName": "案由分类别"
					},
					{
						"tableName": "PNSHJ_HOD_CORT_INFO",
						"chineseName": "法院开庭公告信息表"
					},
					{
						"tableName": "TRD_TOTVAL_CHG_TREND",
						"chineseName": "全球(各国)贸易总额变动趋势"
					},
					{
						"tableName": "TRD_TOTVAL_PARTNER",
						"chineseName": "全球(各国)贸易伙伴明细表"
					},
					{
						"tableName": "PNSHJ_DISCD_EXCTOR",
						"chineseName": "失信被执行人名单表"
					},
					{
						"tableName": "PNSHJ_PERSON_INFO",
						"chineseName": "案件涉及人员(机构)基本信息"
					}
				]
			}
		]

		let antTree = this.changeTreeData(originData);
		antTree.map(p => {
			antdTree.push(new NzTreeNode(p));
		});
		this.nodes = antdTree;
	}

	transformTreeData(data: any): void {
		data['title'] = data['typeName'];
		data['key'] = data['typeCode'];
		if (data.children) {
			data['selectable'] = false;
			data.children.map(p => {
				if (p.tableName) {
					p['title'] = `${p['tableName']}(${p['chineseName']})`;
					p['key'] = p['tableName'];
					p['isLeaf'] = true;
				} else {
					this.transformTreeData(p);
				}
			})
		} else {
			data['selectable'] = false;
			data['isLeaf'] = true;
		}
	}

	changeTreeData(data: any): any {
		data.map(p => {
			this.transformTreeData(p);
		})

		return data;
	}

	page(e): void {
		console.log(e)
	}
}